package com.zeyi.blog.handler;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.zeyi.blog.dto.Result;
import com.zeyi.blog.dto.StatusCode;
import io.jsonwebtoken.SignatureException;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 黎先森
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DataAccessException.class)
    public Result dataAccess(DataAccessException e) {
        Throwable cause = e.getCause();
        if (cause instanceof MySQLIntegrityConstraintViolationException) {
            return new Result(false, StatusCode.REP_KEY, "操作失败");
        }
        return new Result(false, StatusCode.ERROR, "操作失败");
    }

    @ExceptionHandler(SignatureException.class)
    public Result signature(SignatureException e) {
        return new Result(false, StatusCode.BAD_TOKEN, "操作失败");
    }

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        return new Result(false, StatusCode.ERROR, "服务错误");
    }
}
